package com.itheima.reggie.controller;

import com.itheima.reggie.bean.AddressBook;
import com.itheima.reggie.common.R;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 获取用户所有地址
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list() {
        List<AddressBook> list = addressBookService.list();
        return list != null ? R.success(list) : R.error("获取失败");
    }

    /**
     * 添加地址
     * @param addressBook
     * @return
     */
    @PostMapping
    public R<String> addAddress(@RequestBody AddressBook addressBook) {
        int row = addressBookService.addAddress(addressBook);
        return row > 0 ? R.success("添加成功") : R.error("添加失败");
    }

    /**
     * 修改地址
     * @param addressBook
     * @return
     */
    @PutMapping
    public R<String> updateAddress(@RequestBody AddressBook addressBook) {
        int row = addressBookService.updateAddress(addressBook);
        return row > 0 ? R.success("修改成功") : R.error("修改失败");
    }

    /**
     * 删除地址
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteAddress(@RequestParam Long ids) {
        int row = addressBookService.deleteAddress(ids);
        return row > 0 ? R.success("删除成功") : R.error("删除失败");
    }

    /**
     * 查询单个地址
     * @param addressId
     * @return
     */
    @GetMapping("/{addressId}")
    public R<AddressBook> addressFindOne(@PathVariable Long addressId) {
        AddressBook addressBook = addressBookService.addressFindOne(addressId);
        return addressBook != null ? R.success(addressBook) : R.error("该地址不存在");
    }

    /**
     * 设置默认地址
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    public R<String> setDefaultAddress(@RequestBody AddressBook addressBook) {
        int row = addressBookService.setDefaultAddress(addressBook);
        return row > 0 ? R.success("操作成功") : R.error("操作失败");
    }

    /**
     * 获取默认地址
     * @return
     */
    @GetMapping("default")
    public R<AddressBook> getDefaultAddress() {
        AddressBook addressBook = addressBookService.getDefaultAddress();
        return addressBook != null ? R.success(addressBook) : R.error("获取默认地址失败");
    }
}
